﻿// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	SPFileExts.cs
//  Developer:	Igor Solomatov
//  Created:	05.03.2013
// 
// -------------------- iSharePoint -------------------- //

using System;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Smart.Common
{
	public static class SPFileExts
	{
		/// <summary>
		/// Reads whole file
		/// </summary>
		public static byte[] ReadFile(this SPFile file)
		{
			return
				file.Exists && file.LockType != SPFile.SPLockType.Exclusive
					? file.OpenBinary(SPOpenBinaryOptions.SkipVirusScan)
					: null;
		}

		/// <summary>
		/// Reads whole file stream
		/// </summary>
		public static Stream ReadFileStream(this SPFile file)
		{
			return
				file.Exists && file.LockType != SPFile.SPLockType.Exclusive
					? file.OpenBinaryStream(SPOpenBinaryOptions.SkipVirusScan)
					: null;
		}

		/// <summary>
		/// Saves whole file
		/// </summary>
		public static bool SaveFile(this SPFile file, byte[] data, bool overwrite)
		{
			if (file.Exists && (!overwrite || file.LockType != SPFile.SPLockType.None))
				return false;

			file.SaveBinary(data);

			return true;
		}

		/// <summary>
		/// Saves whole file stream
		/// </summary>
		public static bool SaveFile(this SPFile file, Stream data, bool overwrite)
		{
			if (file.Exists && (!overwrite || file.LockType != SPFile.SPLockType.None))
				return false;

			file.SaveBinary(data);

			return true;
		}

		/// <summary>
		/// Returns full file url
		/// </summary>
		public static string GetFullUrl(this SPFile file)
		{
			return SPUrlUtility.CombineUrl(file.Web.Url, file.Url);
		}

		/// <summary>
		/// Returns web-relative file url
		/// </summary>
		public static string GetWebRelativeUrl(this SPFile file)
		{
			return file.Url.TrimStart('/');
		}

		/// <summary>
		/// Returns server-relative file url
		/// </summary>
		public static string GetServerRelativeUrl(this SPFile file)
		{
			return file.ServerRelativeUrl;
		}
	}
}